<?
	class TreeDictionaryController extends Controller
	{
		private function query($code)
		{
			return new Query('dic_' . $code);
		}
		
		public function read($node = 'root', $code)
		{
			$query = $this->query($code);
			$id = $node == 'root' ? null : $node;
			$where = array('eq' => array('parent_id', $id));
			$query->where($where);
			$data = array();
			
			foreach($query->results() as $row)
			{
				$where['eq'][1] = $row['id'];
				$count = $this->query($code)
							   ->where($where)
							   ->count();
				
				$row['count'] = $count;
				$row['expandable'] = ($count > 0);
				
				$data[] = $row;
			}	
			
			return array(
				'success' => true,
				'data' => $data
			);		
		}
		
		public function create($id, $code, $data)
		{
			$query = $this->query($code);			
			$data->parent_id = $id == 'root' ? null : $id;
			
			$id = $query->insert($data);
			$data = $this->query($code)
						 ->where("id = $id")
						 ->result();
			
			return array(
				'success' => true, 
				'data' => $data
			);
		}
		
		public function move($id, $parent_id, $code)
		{
			$query = $this->query($code);
			$data = array('parent_id' => $parent_id == 'root' ? null : $parent_id);
			
			$query->where("id = $id")
				  ->update($data);
			
			return array(
				'success' => true,
				'data' => array('id' => $id)
			);			
		}
		
		public function update($id, $code, $data)
		{
			$query = $this->query($code);
			$query->where("id = $id")
				  ->update($data);
				  
			$data = $this->query($code)
						 ->where("id = $id")
						 ->result();
			
			return array(
				'success' => true, 
				'data' => $data
			);			
		}
		
		public function remove($id, $parent_id, $code)
		{				  
			$count = $this->query($code)
				 ->where("parent_id = $id")
				 ->count();

			if($count)
			{			
				return array(
					'success' => false,
					'data' => 'Удаление невозможно, запись содержит дочерние записи.'
				);	
			}
			
			$this->query($code)
				 ->where("id = $id")
				 ->remove();
				 
			return array(
				'success' => true
			);			  
		}
	}
?>